package com.epfresh.supplier.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.widget.tablayout.CommonTabLayout;
import com.epfresh.api.widget.tablayout.TabEntity;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.fragment.OrderFragment;

import java.util.ArrayList;

public class OrderMoreActivity extends BaseActivity implements OnTabSelectListener {

    private CommonTabLayout lyTab;
    private ViewPager vp;
    //private FragmentManager fragmentManager;
    private OrderFragment onlineFragment;
    private OrderFragment nowFragment;
    private OrderFragment joinFragment;

    private OrderFragment currentFragment;
    private int currentFragmentIndex;
    int pageCount = 3;

    int orderType;//10线上 20 现场 30 联营

    ArrayList<String> types;//订单列表类别 0,待支付 1,未完成, 2,已完成 3,全部订单
    //待支付 2待发货 3 待收货 4 拒签（不显示） 5退款 6 交易取消 7 交易成功 9 待评价 10减免退
    boolean typeFlag;//订单类别展示开关
    int type;//订单列表类别 1,待支付 2,未完成,3已完成 4全部订单

    private LinearLayout llGrid;
    private GridView gvType;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_more);
        //fragmentManager = getSupportFragmentManager();

        //toolbarTitle.setText(R.string.post_product);
        ivBack.setVisibility(View.VISIBLE);
        initData(savedInstanceState);
        //根据tag寻找fragment
        //initFragment();
        //初始化view
        initView();
        //加载数据


    }

    @Override
    protected View getToolBar() {
        View actionbar = inflaterView(R.layout.actionbar_order_layout, null);

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.action_bar_height));
        actionbar.setLayoutParams(lp);

        toolbarTitle = (TextView) actionbar.findViewById(R.id.toolbar_title);/* 标题 用于子类 设置标题 */
        rightbtn = (TextView) actionbar.findViewById(R.id.rightbtn);
        righticon = (ImageView) actionbar.findViewById(R.id.righticon);//
        ivBack = (ImageView) actionbar.findViewById(R.id.baseback);
        tvBack = (TextView) actionbar.findViewById(com.epfresh.api.R.id.tv_back);
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivBack.performClick();
            }
        });
        tvBack.setVisibility(View.VISIBLE);
        baseback = ivBack;
        basetitle = toolbarTitle;
        ivBack.setOnClickListener(this);
        return actionbar;
    }


    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.toolbar_title:
            case R.id.toolbar_title_flag:
                Log.i("typeFlag", "开始加载" + typeFlag);
                if(typeFlag){
                    llGrid.setVisibility(View.GONE);
                    Log.i("typeFlag", "隐藏" + typeFlag);

                    typeFlag = false;
                }else {
                    typeFlag = true;
                    llGrid.setVisibility(View.VISIBLE);
                    Log.i("typeFlag", "显示" + typeFlag);

                }
                break;
            case R.id.ll_grid:
                llGrid.setVisibility(View.GONE);
                typeFlag = false;
                break;
            case R.id.righticon:
                Intent search = new Intent(this, OrderSearchActivity.class);
                startActivity(search);
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        String status = intent.getStringExtra("status");

        setIntent(intent);

        if ("0".equals(status)){
            vp.setCurrentItem(1);
            lyTab.setCurrentTab(1);
        }

        if ("2".equals(status)){
            vp.setCurrentItem(2);
            lyTab.setCurrentTab(2);
        }

        refreshList();

    }

    private void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            currentFragmentIndex = savedInstanceState.getInt(Constant.KEY_HOME_STATE_INDEX);
            getIntent().putExtra("orderType", savedInstanceState.getInt("orderType"));
        }
        orderType = getIntent().getIntExtra("orderType", 10);
    }

    void initTimeList(){
        types = new ArrayList<>();
        //待支付 2待发货 3 待收货 4 拒签（不显示） 5退款 6 交易取消 7 交易成功 9 待评价 10减免退

        types.add(0,"全部订单");
        types.add(1, "待付款");
        types.add(2,"待发货");
        types.add(3,"待收货");
        types.add(4,"交易取消");
        types.add(5, "交易成功");
        gvType.setAdapter(new CommonAdapter<String>(this, types, R.layout.item_string_gird) {
            TextView lastView;

            @Override
            public void convert(final ViewHolder holder, final String bean) {
                holder.setText(R.id.tv_string, bean);
                holder.setOnClickListener(R.id.tv_string, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (lastView == null) {
                        } else {
                            lastView.setTextColor(getResources().getColor(R.color.TextColordarker));
                            lastView.setBackgroundResource(R.drawable.btn_white);
                        }
                        type = types.indexOf(bean);
                        toolbarTitle.setText(bean);
                        llGrid.setVisibility(View.GONE);
                        typeFlag = false;
                        holder.getView(R.id.tv_string).setBackgroundResource(R.drawable.btn_red);
                        lastView = holder.getView(R.id.tv_string);
                        lastView.setTextColor(getResources().getColor(R.color.red));
/*                        onlineFragment.requestSucceedCount = 0;
                        onlineFragment.typeState = type;
                        onlineFragment.refresh();
                        nowFragment.requestSucceedCount = 0;
                        nowFragment.typeState = type;
                        nowFragment.refresh();*/
                        switch (type){
                            case 0://首页按钮0,1,2,5按钮对应本页面1,2,3,0；
                            case 1:
                            case 2:
                            case 3:
                                break;
                            case 4://交易取消
                            case 5:
                                type+=2;
                                break;
                        }


                        if (onlineFragment == null) {
                            onlineFragment = new OrderFragment();
                        }
                        if (nowFragment == null) {
                            nowFragment = new OrderFragment();
                        }
                        if(joinFragment == null)
                            joinFragment = new OrderFragment();
                        joinFragment.typeState = type;
                        joinFragment.typeOnline = 30;
                        joinFragment.refresh();

                        onlineFragment.typeState = type;
                        onlineFragment.typeOnline = 10;
                        onlineFragment.refresh();

                        nowFragment.typeState = type;
                        nowFragment.typeOnline = 20;
                        nowFragment.refresh();

                    }
                });
            }
        });
    }

    private void initView() {
        ivBack.setVisibility(View.VISIBLE);
        righticon.setImageResource(R.mipmap.order_search);
        righticon.setVisibility(View.VISIBLE);
        righticon.setOnClickListener(this);
        llGrid = (LinearLayout)findViewById(R.id.ll_grid);
        llGrid.setOnClickListener(this);
        gvType = (GridView)findViewById(R.id.gv_type);
        type = getIntent().getIntExtra("type",5);////首页按钮0,1,2,5按钮对应本页面1,2,3,0
        if(type<5){
            ++type;
        }
        if(type==5){
            type=0;
        }
        initTimeList();
        setToolbarTitle(types.get(type));
        ImageView flag = (ImageView)findViewById(R.id.toolbar_title_flag);
        flag.setOnClickListener(this);
        toolbarTitle.setOnClickListener(this);
        flag.setVisibility(View.VISIBLE);

        vp = (ViewPager) findViewById(R.id.vp);
        lyTab = (CommonTabLayout) findViewById(R.id.ly_navigation);
/*        if (orderType == 0) {//线上
            pageCount = 0;
        } else if (orderType == 1) {//线下
            pageCount = 1;
        }*/

        String[] mTitles = {"线上订单","现场订单","联营订单"};

        ArrayList<TabEntity> mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], 0, 0));
        }
        lyTab.setTabData(mTabEntities);
        lyTab.setOnTabSelectListener(this);
        vp.setOffscreenPageLimit(0);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentFragmentIndex = position;
                lyTab.setCurrentTab(currentFragmentIndex);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        vp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                //    (0, "线上订单"),
                //    (1, "现场订单"),
                if (position == 0) {
                    if (onlineFragment == null) {
                        onlineFragment = new OrderFragment();
                        onlineFragment.typeState = type;
                        onlineFragment.typeOnline = 10;
                    }
                    currentFragment = onlineFragment;
                } else if (position == 1) {
                    if (nowFragment == null) {
                        nowFragment = new OrderFragment();
                        nowFragment.typeState = type;
                        nowFragment.typeOnline = 20;
                    }
                    currentFragment = nowFragment;
                }else if(position == 2){
                    if (joinFragment == null) {
                        joinFragment = new OrderFragment();
                        joinFragment.typeState = type;
                        joinFragment.typeOnline = 30;
                    }
                    currentFragment = joinFragment;
                }
                currentFragmentIndex = position;
                return currentFragment;
            }

            @Override
            public int getCount() {
                return pageCount;
            }
        });
        if(orderType == 10){
            currentFragmentIndex = 0;
        }else if(orderType == 20){
            currentFragmentIndex = 1;
        }else {
            currentFragmentIndex = 2;
        }

        vp.setCurrentItem(currentFragmentIndex);

    }

    //当前选中的tab
    @Override
    public void onTabSelect(int position) {
        vp.setCurrentItem(position);
//        selectPage(position);
    }

    //再次点击当前选中的tab
    @Override
    public void onTabReselect(int position) {

    }

/*    //根据tag寻找fragment
    public void initFragment() {
        onlineFragment = (OrderFragment) fragmentManager.findFragmentByTag(Constant.TAG_SOLD_IN_FRAGMENT);
        nowFragment = (OrderFragment) fragmentManager.findFragmentByTag(Constant.TAG_SOLD_DRAFT_FRAGMENT);
        joinFragment = (OrderFragment) fragmentManager.findFragmentByTag(Constant.TAG_SOLD_DRAFT_FRAGMENT);
    }*/
/*


    private void addCashProduct() {
        Intent intent = new Intent(this, ProductAddActivity.class);
        //现售1
        if (orderType == 1) {//现货
            intent.putExtra(Constant.TYPE, "1");
        } else if (orderType == 2) {//预售
            intent.putExtra(Constant.TYPE, "2");
        }

        intent.putExtra("is_first", true);

        startActivityForResult(intent, 0x45);
    }
    private void addProduct() {
        Intent intent = new Intent(this, ProductAddCategoryActivity.class);
        //现售1
        if (orderType == 1) {//现货
            intent.putExtra(Constant.TYPE, "1");
        } else if (orderType == 2) {//预售
            intent.putExtra(Constant.TYPE, "2");
        }

        intent.putExtra("is_first", true);

        startActivityForResult(intent, 0x65);
    }

    private void addPreProduct() {
        Intent intent = new Intent(this, ProductAddActivity.class);
        //预售2
        intent.putExtra(Constant.TYPE, "2");
        intent.putExtra("is_first", true);
        startActivityForResult(intent, 0x45);
    }
*/

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //记录当前fragment的下标
        outState.putInt(Constant.KEY_HOME_STATE_INDEX, currentFragmentIndex);
        //outState.putInt("orderType", orderType);
        super.onSaveInstanceState(outState);
    }

    public void refreshList() {
        if (onlineFragment != null)
            onlineFragment.refresh();

        if (nowFragment != null)
            nowFragment.refresh();
        if(joinFragment != null)
            joinFragment.refresh();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0x65 && resultCode == RESULT_OK) {
            refreshList();
        }
    }
}
